package cn.semyes.ylipfilter.controller.status;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.semyes.ylipfilter.bean.Constants;
import cn.semyes.ylipfilter.bean.User;
import cn.semyes.ylipfilter.common.util.CreateJsonObject;
import cn.semyes.ylipfilter.common.util.CreateRandomPwd;
import cn.semyes.ylipfilter.common.util.GetCurDateTime;
import cn.semyes.ylipfilter.common.util.GetHttpJsonobject;
import cn.semyes.ylipfilter.common.util.GetRemoteApiUtils;
import cn.semyes.ylipfilter.common.util.R;
import cn.semyes.ylipfilter.entity.ExcludeIpEntity;
import cn.semyes.ylipfilter.entity.UserEntity;
import cn.semyes.ylipfilter.service.BaiduAccountService;
import cn.semyes.ylipfilter.service.BusinessBridgeService;
import cn.semyes.ylipfilter.service.ExceptionOneWeekIpService;
import cn.semyes.ylipfilter.service.ExcludeIpService;
import cn.semyes.ylipfilter.service.StatusService;
import cn.semyes.ylipfilter.service.UserService;


@RestController
@RequestMapping("/user")
public class StatusController {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private JSONObject data = null;
	private CreateJsonObject createJsonObject;
	private GetHttpJsonobject getHttpJsonobject; 
	
	
	private String pwd = null;
	private JSONObject jsonParams;
	private String bodyStr;
	private JSONObject jsonObject;
	private JSONObject userInfo;
	private JSONObject temp;
	private JSONArray ipList;
	
	private List<String> curDayIpList;
	private List<String> list;
	
	private int index = 0;
	private Calendar c;
	private int totalNum = 0;
	private String tempId;
	
	private UserEntity userEntity;
	private User user;
	
	private int userId = 0;
	private int appId = 3;
	private String visitTime = null;
	private String create_time = null;
	private String companyName = null;
	
	private ExcludeIpEntity excludeIpEntity;
	
	@Autowired
	private BusinessBridgeService businessBridgeService;
	
	//private static MessageDigestPasswordEncoder passEncoder = new MessageDigestPasswordEncoder("MD5");
	private ExceptionOneWeekIpService exceptionOneWeekIpService = GetRemoteApiUtils.getRemoteService(ExceptionOneWeekIpService.class,"exceptionOneWeekIpService");
	
	@Autowired
	private ExcludeIpService excludeIpService;
	
	@Autowired
	private BaiduAccountService baiduAccountService;
	
	@Autowired
	private UserService userService;
	
	@GetMapping("/getUserInfo.do")
	public R getUser(HttpServletRequest request) {
		
		createJsonObject= new CreateJsonObject();
    	getHttpJsonobject = new GetHttpJsonobject();
   
    	jsonParams = new JSONObject();
    	userInfo = new JSONObject();
    	ipList = new JSONArray();
    	

    	user = new User();
    	getBdUserInfo(request);
    	
    	String bodyStr = "{"+
				"\"header\":{" + 
				"\"token\":\"de86e485832d365067078dda4cd2d2eb\"," + 
				"\"accessToken\": \""+ user.getAccessToken() + 
				"\"}," + 
				"\"body\":{" + 
				"\"accountFields\":" +
					  "[\"userId\",\"balance\",\"cost\",\"payment\",\"budgetType\",\"budget\",\"regionTarget\",\"excludeIp\",\"openDomains\",\"regDomain\",\"budgetOfflineTime\",\"weeklyBudget\",\"userStat\",\"isDynamicCreative\",\"dynamicCreativeParam\",\"pcBalance\",\"mobileBalance\"]" +
				"}}";
		
		data = getHttpJsonobject.httpsRequest(Constants.BAIDU_SEARCH_API+"/AccountService/getAccountInfo", "POST", bodyStr);
		logger.info("后台请求百度获取json格式的用户数据:"+data);
		user.setUserDomain(data.getJSONObject("body").getJSONArray("data").getJSONObject(0).getString("regDomain"));
		setBdUserInfo(request,"cur_domain",user.getUserDomain());
		
		setBdUserInfo(request,"cur_bd_userId",data.getJSONObject("body").getJSONArray("data").getJSONObject(0).getString("userId"));
		//随机生成密码
		pwd = CreateRandomPwd.generateString(10);  
		ipList =data.getJSONObject("body").getJSONArray("data").getJSONObject(0).getJSONArray("excludeIp");
		if (ipList != null) {
			logger.info("ip排除列表："+ ipList.toString());		
			//保存用户的ip排除列表
			ipSave(user.getUserDomain(),ipList); 
		} else {
			excludeIpService.deleteAll(user.getUserDomain());
		}
		
		//判断是否新用户注册
		jsonObject = getHttpJsonobject.httpsRequest(Constants.REGISTE_API, "POST", "domain="+user.getUserDomain()+"&username="+user.getUserMobile()+"&password="+pwd);
		tempId= jsonObject.getJSONObject("attributes").getString("userId");
		if (tempId != null) {
			setBdUserInfo(request,"cur_userId",tempId);
			user.setUserId(tempId);
			if (request.getSession().getAttribute("saveToKad") == null) {
				request.getSession().setAttribute("saveToKad", "true");
				//保存到kad的用户数据
				saveBaiduAccount(Integer.parseInt(data.getJSONObject("body").getJSONArray("data").getJSONObject(0).getString("userId")),
						user.getUsername(),
						request.getSession().getAttribute("cur_refreshToken").toString(),
						request.getSession().getAttribute("cur_datatime").toString(),
						request.getSession().getAttribute("cur_datatime").toString()
						);
				companyName = request.getSession().getAttribute("cur_username").toString();
				userId = Integer.parseInt(request.getSession().getAttribute("cur_bd_userId").toString());
				visitTime = request.getSession().getAttribute("cur_datatime").toString();
				saveBusinessBridge(companyName,request.getSession().getAttribute("mobile_num").toString(),userId,visitTime);
			}
						
			if (userService.getUser(user.getUserDomain()) == null) {
				userSave(getUserEntity(user.getUserId(), user.getUsername(), user.getUserDomain(), pwd));
			}
		}else if (tempId == null) {
			return R.ok().put("data", -1);
		
		}
		
		logger.info("tempid和userid:"+ tempId+"和"+user.getUserId());
		return R.ok().put("data", userInfo());
		
	}
	
	//保存用户
	private void userSave(UserEntity userEntity) {
		
		userService.saveUser(userEntity);
	}
	
	//从session中获取用户信息
	private void getBdUserInfo(HttpServletRequest request) {
		user.setAccessToken(request.getSession().getAttribute("cur_accessToken").toString());
		user.setUsername(request.getSession().getAttribute("cur_username").toString());
		user.setUserMobile(request.getSession().getAttribute("mobile_num").toString());
		//logger.info("session中的accesstoken和username:"+user.getAccessToken()+":::"+user.getUsername()+"::手机:::"+user.getUserMobile());
		
	}
	
	//设置用户信息到session中 
	private void setBdUserInfo(HttpServletRequest request,String sessionName, String sessionStr) {
		request.getSession().setAttribute(sessionName, sessionStr);
	}
	
	//保存ip排除列表
	public void ipSave(String domain, JSONArray arr) {
		excludeIpEntity = new ExcludeIpEntity();
		for (index = 0; index < arr.size();index++) {
			
			if (excludeIpService.getIpExist(domain, arr.getString(index)) == null) {
				excludeIpService.saveExcludeIp(domain, arr.getString(index));
			}	
		}
	}
	
	//获取User信息
	public UserEntity getUserEntity(String userId, String username, String domain, String pwd) {
		userEntity = new UserEntity();
		userEntity.setUserid(userId);
		userEntity.setUsername(username);
		userEntity.setDomain(domain);
		userEntity.setPassword(pwd);
		return userEntity;
	}
	
	//获取返回的用户数据
	public JSONObject userInfo() {
		c = Calendar.getInstance();		
		temp = getYesterdayIpData(user.getUsername(), c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+(c.get(Calendar.DATE)-1));
		if (temp != null) {
			
			userInfo.put("site", user.getUserDomain());
			userInfo.put("totalClick", temp.getString("totalClick"));
			userInfo.put("totalIp", temp.getString("totalPV"));
			return userInfo;
		}
		
		userInfo.put("site", user.getUserDomain());
		userInfo.put("totalClick", 0);
		userInfo.put("totalIp", 0);
		return userInfo;
	}
	
	//获取当天ip数据
	public JSONObject getYesterdayIpData(String userId,String today) {
		list = exceptionOneWeekIpService.getOneIp(userId, today);
		jsonObject = new JSONObject();
		curDayIpList = new ArrayList<>();
		if (list != null) {
			for (index = 0; index < list.size(); index++) {
	         	jsonObject = JSONObject.parseObject(list.get(index));
	         	totalNum += Integer.parseInt(jsonObject.getString("mcount"));
	         	ipList.add(jsonObject.getString("mcount"));
	 		}
			JSONObject json = new JSONObject();
			json.put("totalClick", totalNum);
			json.put("totalPV", removeDuplicate(curDayIpList));
			totalNum = 0;
			return json;
		}
		return null;
		
	}
	
	private void saveBaiduAccount(int user_id,String user_name, String refresh_token, String create_time, String recent_time) {
		if (baiduAccountService.selectByUserId(user_id) != null) {
			baiduAccountService.updateUser(user_id, recent_time);
		} else {
			baiduAccountService.saveUser(user_id, user_name, refresh_token, create_time, recent_time);
		}
		
	}
	
	//ip去重
	public int removeDuplicate(List<String> list) {   
		HashSet hset = new HashSet(list);   
		list.clear();   
		list.addAll(hset);   
		return list.size();   
	}  
	
	//保存用户到kad
	private void saveBusinessBridge(String companyName, String phoneNumber, int userId, String visitTime) {
//		getCurDateTime = new GetCurDateTime();		
//		create_time = getCurDateTime.getCurTime();	
		businessBridgeService.saveUser(userId,companyName, phoneNumber,visitTime,appId,visitTime);
		
	}
}
